package com.example.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.model.EncryptEnvelope;
import com.example.service.NationCaService;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * @ClassName NationController
 * @Description TODO
 * @Author kun
 * @Date 2024-10-22 11:25
 * @Version 1.0
 */

@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("nation")
public class NationController {
    @Resource
    private NationCaService nationService;

    private final String decryptDir = "decrypts";
    private final String uploadDirs = "uploads";

    /**
     * 获取配置信息
     * @return
     */
    @RequestMapping("getconfig")
    public String getConfig() {
        String result = nationService.getNaConfig();
        return result;
    }

    /**
     * 获取登录二维码
     * @return
     */

    @RequestMapping("getLoginQrCode")
    public JSONObject getLoginQrCode() {
        String result = nationService.getLoginQrCode();
        JSONObject json = JSONUtil.parseObj(result);
        return json;
    }

    /**
     * 获取登录二维码状态扫码状态
     * @param tid
     * @return
     */
    @RequestMapping("queryScannedStatus")
    public JSONObject queryScannedStatus(@RequestParam("tid") String tid) {
        String result = nationService.queryScannedStatus(tid);
        JSONObject json = JSONUtil.parseObj(result);
        return json;
    }

    /**
     * 获取用户信息
     * @param tid
     * @return
     */
    @RequestMapping("getUserInfo")
    public String getUserInfo(@RequestParam("tid") String tid) {
        String result = nationService.getUserInfo(tid);
        return result;
    }

    @RequestMapping("gsBodyLogin")
    public JSONObject gsBodyLogin(@RequestParam("threeInOneCode") String threeInOneCode) {
        JSONObject result = nationService.gsBodyLogin(threeInOneCode);
        return result;
    }

    /**
     * 获取加密二维码
     * @return
     */
    @RequestMapping("getEnQrcode")
    public JSONObject getEnQrcode() {
        String result = nationService.getEnQrCode();
        JSONObject json = JSONUtil.parseObj(result);
        return json;
    }

    /**
     * 查询加密二维码扫描状态
     * @param tid
     * @return
     */
    @RequestMapping("queryEnScannedStatus")
    public JSONObject queryEnScannedStatus(@RequestParam("tid") String tid){
        String result=nationService.queryEnScannedStatus(tid);
        JSONObject json = JSONUtil.parseObj(result);
        return json;
    }

    /**
     * 加密消息
     * @param tid
     * @param msg
     * @return
     */
    @RequestMapping("encryptMsg")
    @ResponseBody
    public String encryptMsg(@RequestParam("tid") String tid,@RequestParam("msg")String msg){
        String result=nationService.encryptMsg(tid,msg);
        return result;
    }

// 解密流程
//1：生成解密二维码,扫码，
//2: 检查到扫码后，根据tid获取解密用户信息
//3：上传信封信息后在app端输入密码
//4:获取解密信息

    /**
     * 获取解密二维码
     *
     * @return
     */
    @RequestMapping("getDeQrCode")
    @ResponseBody
    public JSONObject getDeQrCode(@RequestParam("decyptUserType") String decyptUserType,@RequestParam("threeInOneCode") String threeInOneCode,@RequestParam("idCardHash")  String idCardHash) {
        String result = nationService.getDeQrCode(decyptUserType,threeInOneCode,idCardHash);
        JSONObject json = JSONUtil.parseObj(result);
        return json;
    }

    /**
     * 查询解密二维码扫描状态
     * @param tid
     * @return
     */
    @RequestMapping("queryDeScannedStatus")
    @ResponseBody
    public JSONObject queryDeScannedStatus(@RequestParam("tid") String tid) {
        String result = nationService.queryDeScannedStatus(tid);
        JSONObject json = JSONUtil.parseObj(result);
        return json;
    }

    /**
     * 获取解密用户信息
     * @param tid
     * @return
     */
    @RequestMapping("getDecryptUserInfo")
    @ResponseBody
    public String getDecryptUserInfo(@RequestParam("tid") String tid) {
        String result = nationService.getDecryptUserInfo(tid);
        return result;
    }

    /**
     * 上传加密信封信息
     * @param encryptEnvelope
     * @return
     */
    @RequestMapping("uploadEncryptEnvelope")
    public String uploadEncryptEnvelope(HttpServletRequest request) throws IOException {
        //获取请求体中的数据
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
        }

        bufferedReader.close();
        EncryptEnvelope encryptEnvelope=JSONUtil.toBean(stringBuilder.toString(),EncryptEnvelope.class);
        String result = nationService.uploadEncryptEnvelope(encryptEnvelope);
        return result;
    }

    /**
     * 获取解密信息
     * @param tid
     * @return
     */
    @RequestMapping("getDecryptMsg")
    public JSONObject decryptMsg(@RequestParam("tid") String tid) {
        String result = nationService.getDecryptMsg(tid);
        JSONObject json = JSONUtil.parseObj(result);
        return json;
    }

    /**
     * 获取签名二维码
     * @return
     */
    @RequestMapping("getSignQrCode")
    public String getSignQrCode(@RequestParam("msg") String msg) {
        String result = nationService.getSignQrCode(msg);
        return result;
    }
    /**
     * 查询签名二维码扫描状态
     * @param tid
     * @return
     */
    @RequestMapping("querySignScannedStatus")
    public JSONObject querySignScannedStatus(@RequestParam("tid") String tid) {
        String result = nationService.querySignScannedStatus(tid);
        JSONObject json = JSONUtil.parseObj(result);
        return json;
    }

    /**
     * 获取签名结果
     * @param tid
     * @return
     */
    @RequestMapping("getSignResult")
    public String getSignResult(@RequestParam("tid") String tid) {
        String result = nationService.getSignResult(tid);
        return result;
    }
    /**
     * 验证签名
     * @param msg
     * @param sign
     * @param alogrithm
     * @return
     */
    @RequestMapping("verifySign")
    public String verifySign(@RequestParam("msg") String msg, @RequestParam("sign") String sign, @RequestParam("alogrithm") String alogrithm) throws UnsupportedEncodingException {
        //使用url decode解码
        //sign = java.net.URLDecoder.decode(sign, "UTF-8");
        //msg=java.net.URLDecoder.decode(msg,"UTF-8");
        String result = nationService.verifySign(msg, sign, alogrithm);
        return result;
    }

    @RequestMapping("pdfback")
    public String pdfBack(HttpServletRequest request) {
        String platFormCode = request.getParameter("platFormCode");
        String systemCode = request.getParameter("systemCode");
        String fileKey = request.getParameter("fileKey");
        String result = nationService.getSignPdfCallback(platFormCode,systemCode,fileKey);
//        JSONObject json = JSONUtil.parseObj(result);
//        return json;
        return result;
    }

    @PostMapping("/upload")
    public JSONObject handleFileUpload(@RequestParam("file") MultipartFile file) {
        JSONObject result = new JSONObject();
        if (file.isEmpty()) {
            result.put("code", 500);
            return result;
        }
        try {
            // 保存文件到指定路径
            String uploadDir = "uploads"; // 上传目录
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() +extName;
            File destFile = new File(dir, fileName);
            FileOutputStream fos = new FileOutputStream(destFile);
            fos.write(file.getBytes());
            fos.close();
            result.put("code", 200);
            result.put("msg", "文件上传成功: " + fileName);
            result.put("fileName", fileName);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", "文件上传失败");
            return result;
        }
    }

    @RequestMapping("unzipFile")
    public JSONObject unzipFile(HttpServletRequest request) throws Exception {
        JSONObject result = new JSONObject();
        String fileKey = request.getParameter("fileKey");
        Map map = nationService.decryptUnzipFile(fileKey);
        if(map==null){
            result.put("code", 500);
            result.put("msg","解压缩文件失败");
        }
        result.put("code", 200);
        result.put("data",map);
        return result;
    }
    @RequestMapping("decyptFile")
    public JSONObject decryptUnzipFile(HttpServletRequest request) throws Exception {
        JSONObject result = new JSONObject();
        String fileKey = request.getParameter("fileKey");
        String decryptPassword = request.getParameter("decryptPassword");
        String fileName= nationService.decryptFile(fileKey,decryptPassword);
        if(StrUtil.isEmpty(fileName)){
            result.put("code", 500);
            result.put("msg","解密文件失败");
        }
        result.put("code", 200);
        result.put("msg","解密文件成功");
        result.put("data",fileName);
        return result;
    }
    private List<String> findFiles(Path directory) {
        if (directory == null || !Files.exists(directory)) {
            System.err.println("指定的目录不存在: " + directory);
            return new ArrayList<>();
        }

        List<String> files = new ArrayList<>();
        try {
            Files.walk(directory)
                    .filter(Files::isRegularFile)
                    .map(Path::toString)
                    .forEach(files::add);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return files;
    }
    @GetMapping("/download")
    public void downloadFile(@RequestParam String fileName,HttpServletRequest request, HttpServletResponse response) throws IOException {

        String outDir=decryptDir+File.separator+fileName;
        List<String> encFiles = findFiles(Paths.get(outDir));
        if (encFiles.isEmpty()) {
            throw new FileNotFoundException("未找到文件: " + fileName);
        }
        String downloadName=encFiles.get(0).substring(encFiles.get(0).lastIndexOf(File.separator)+1);
        InputStream in = new FileInputStream(encFiles.get(0));

        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + downloadName);

        OutputStream out = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        in.close();
        out.close();
    }

    @GetMapping("/download2")
    public void downloadFile2(@RequestParam String fileName,HttpServletRequest request, HttpServletResponse response) throws IOException {

        String outDir=uploadDirs+File.separator+fileName;
        List<String> encFiles = findFiles(Paths.get(outDir));
        if (encFiles.isEmpty()) {
            throw new FileNotFoundException("未找到文件: " + fileName);
        }
        String downloadName=encFiles.get(0).substring(encFiles.get(0).lastIndexOf(File.separator)+1);
        InputStream in = new FileInputStream(encFiles.get(0));
        if(fileName.toLowerCase().endsWith(".pdf")){
            response.setContentType("application/pdf");
        }else{
            response.setContentType("application/octet-stream");
        }

        response.setHeader("Content-Disposition", "attachment; filename=" + downloadName);

        OutputStream out = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        in.close();
        out.close();
    }

    @RequestMapping("uploadFileUrl")
    public String uploadFileUrl(HttpServletRequest request) throws IOException {
       // String url="https://yhgx.oss-cn-hangzhou.aliyuncs.com/yhgx/202411/eb5da237-d4d8-4591-aaa0-aba47138d900.pdf";
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
        }

        bufferedReader.close();

        JSONObject json = JSONUtil.parseObj(stringBuilder.toString());
        String url=json.getStr("fileUrl");
        String extName=json.getStr("extName");
        String result=nationService.uploadFileUrl(url,extName);
//        JSONObject result = new JSONObject();
//        result.put("code", 200);
//        result.put("msg", "文件上传成功");
//        result.put("data", value);
        return result;
    }

}
